<template>
  <div class="container">
    <el-card class="table-container">
      <div style="margin: 0 10px 20px 10px">
        <el-form :inline="true" :model="searchForm" ref="searchForm" class="demo-form-inline">
          <el-form-item label="营业厅" prop="id">
            <el-col :span="22">
              <el-select v-model="searchForm.id" filterable placeholder="请选择营业厅" @change="$forceUpdate()">
                <el-option v-for="item in DepartmentList" :key="item.id" :label="item.name" :value="item.id">
                </el-option>
              </el-select>
            </el-col>
          </el-form-item>
          <el-form-item label="检查日期" prop="checkDate" label-width="80px">
            <el-col :span="22">
              <!-- <el-input :rows="5" v-model="searchForm.checkDate" clearable type="text" placeholder="请输入检查日期" />
                -->
              <el-date-picker v-model="searchForm.checkDate" type="daterange" range-separator="至" start-placeholder="开始日期"
                end-placeholder="结束日期">
              </el-date-picker>
            </el-col>
          </el-form-item>
          <el-form-item label="班次类型" prop="shiftType" label-width="80px">
            <el-col :span="22">
              <el-select v-model="searchForm.shiftType" filterable placeholder="请选择班次类型"  @change="$forceUpdate()">
                <el-option v-for="item in shiftType" :key="item.value" :label="item.label" :value="item.value">
                </el-option>
              </el-select>
            </el-col>
          </el-form-item>
          <el-form-item label="当前阶段" prop="currentStage" label-width="80px">
            <el-col :span="22">
              <el-select v-model="searchForm.currentStage" filterable placeholder="请选择当前阶段"  @change="$forceUpdate()">
                <el-option v-for="item in currentStage" :key="item.value" :label="item.label" :value="item.value">
                </el-option>
              </el-select>
            </el-col>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleQuery">查询</el-button>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleChange">重置</el-button>
          </el-form-item>
          <el-form-item>
            <el-button :loading="exportLoading" type="success" plain @click="handleExportExcel">Excel导出</el-button>
          </el-form-item>
        </el-form>
      </div>
      <el-table :data="tableData.list" :header-row-class-name="'table-head-th'" fit v-loading="queryLoading"
        highlight-current-row>
        <el-table-column key="yytname" show-overflow-tooltip prop="yytname" label="营业厅" />
        <el-table-column key="checkDate" show-overflow-tooltip prop="checkDate" label="检查日期" />
        <el-table-column key="shiftType" show-overflow-tooltip prop="shiftType" label="班次类型">
          <template slot-scope="scope">

            <el-tag effect="dark" v-if="scope.row.shiftType == 1"> {{ getShiftTypeFilter(scope.row.shiftType)
            }}</el-tag>
            <el-tag type="warning" effect="dark" v-if="scope.row.shiftType == 2"> {{
              getShiftTypeFilter(scope.row.shiftType) }}</el-tag>
            <el-tag type="success" effect="dark" v-if="scope.row.shiftType == 3"> {{
              getShiftTypeFilter(scope.row.shiftType) }}</el-tag>
          </template>

        </el-table-column>
        <el-table-column key="currentStage" show-overflow-tooltip prop="currentStage" label="当前阶段">
          <template slot-scope="scope">
            <el-tag effect="dark" v-if="scope.row.currentStage == 1"> {{ getCurrentStage(scope.row.currentStage)
            }}</el-tag>
            <el-tag type="success" effect="dark" v-if="scope.row.currentStage == 2"> {{
              getCurrentStage(scope.row.currentStage) }}</el-tag>
            <el-tag type="success" effect="dark" v-if="scope.row.currentStage == 3"> {{
              getCurrentStage(scope.row.currentStage) }}</el-tag>
          </template>

        </el-table-column>

        <el-table-column key="createdName" show-overflow-tooltip prop="createdName" label="创建人" />
        <!-- 表格操作列 -->
        <el-table-column label="操作" fixed="right" width="150">
          <template slot-scope="scope">
            <el-button-group>
              <el-button size="mini" title="查看" type="primary" @click="handleDetail(scope.row)">
                <i class="fa fa-eye" />
              </el-button>
              <el-button v-if="scope.row.shiftType == 3 && scope.row.currentStage == 2" size="mini" title="导出"
                type="success" @click="handleDao(scope.row.checkId, scope.row.yytname, scope.row.createdAt)">
                <i class="fa fa-mail-forward" />
              </el-button>
              <el-button size="mini" title="删除" type="danger" @click="handleDel(scope.row)">
                <i class="fa fa-trash-o" />
              </el-button>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页信息 -->
      <div class="pagination-container">
        <el-pagination background layout="total, prev, pager, next, jumper" @current-change="handlePageChange"
          @size-change="handleSizeChange" :current-page="pageNum" :total="tableData.total">
        </el-pagination>
      </div>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog title="记录详情" :visible.sync="showEditDialog">
      <safety-check-edit :mode="mode" ref="editForm" :record="currentRecord" @after-edit="handleAfterEdit" />
    </el-dialog>
  </div>
</template>

<script>
import { Message } from 'element-ui'
import SafetyCheckApi from '../api/safetyCheck'
import safetyCheckEdit from './safetyCheckEdit'
import ImportExcel from '@/components/ImportExcel'
import store from '../../../store'
import { parseTime } from "../../../utils/index"
import DepartmentApi from "../../department/api/department"
export default {
  name: 'SafetyCheckList',
  components: {
    safetyCheckEdit,
    ImportExcel
  },
  data() {
    return {
      /* 搜索请求数据*/
      searchForm: {},
      pageSize: 10,
      pageNum: 1,
      // 表格数据
      tableData: {
        results: [],
        total: 0
      },
      mode: 'edit',
      // 是否显示添加/编辑对话框
      showEditDialog: false,
      // 当前处理行
      currentRecord: {},
      queryLoading: false,
      exportLoading: false,
      autoWidth: true,
      bookType: 'xlsx',
      shiftType: Array.from(store.getters.dictMap).filter(entry => entry.groupCode === "shift_type"),
      currentStage: Array.from(store.getters.dictMap).filter(entry => entry.groupCode === "current_stage"),
      DepartmentList: []
    }
  },
  mounted() {
    this.init()
    DepartmentApi.queryByCond({}).then(res => {
      if (res.data.code == 200) {
        this.DepartmentList = res.data.data.list
      }
    })
  },


  methods: {
    // 页面初始化
    init() {
      this.handleQuery()
    },
    handleQuery() {
      this.pageNum = 1
      this.query()
    },
    getShiftTypeFilter(value) {
      let targetArr = this.shiftType.filter(item => {
        return item.value == value
      })

      return targetArr[0].label
    },
    getCurrentStage(value,) {
      let targetArr = this.currentStage.filter(item => {
        return item.value == value
      })

      return targetArr[0].label
    },
    handleExportExcel() {
      this.exportLoading = true
      let param = {}
      param = Object.assign({}, this.searchForm)
      SafetyCheckApi
        .queryByCond(param, 0, 0).then(rspData => {
          let datalist = []
          datalist = rspData.data.data.list
          import('@/vendor/Export2Excel').then(excel => {
            const tHeader = [
              '营业厅id',
              '检查日期',
              '班次类型',
              '当前阶段',
              '创建人id',
            ]
            const filterVal = [
              'id',
              'checkDate',
              'shiftType',
              'currentStage',
              'createdBy',
            ]
            const list = datalist
            const data = this.formatJson(filterVal, list)
            excel.export_json_to_excel({
              header: tHeader,
              data,
              filename: '一班三查汇总',
              autoWidth: this.autoWidth,
              bookType: this.bookType
            })
            this.exportLoading = false
          })
        }).catch(error => {
          this.exportLoading = false
          if (error.message !== '') {
            //Message.error(error.message)
          }
        })
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => {
        if(j=="id"){
          return v['yytname']
        }else if(j == "createdBy"){
          return v['createdName']
        }else if(j == "shiftType"){
          let target=   this.shiftType.filter(item=>{
             return item.value== v[j]
          })
          return target[0].label
        }else if (j == "currentStage"){
          let target=   this.currentStage.filter(item=>{
             return item.value== v[j]
          })
          return target[0].label
        }else{
          return v[j]
        }

      }))
    },
    query() {

      return new Promise((resolve, reject) => {
        this.queryLoading = true
        const param = Object.assign({}, this.searchForm)
        if(param.checkDate){
          param.startTime=parseTime(param.checkDate[0], '{y}-{m}-{d} 00:00:00')
          param.endTime=parseTime(param.checkDate[1], '{y}-{m}-{d} 24:00:00')
          param.checkDate=undefined
        }


        SafetyCheckApi
          .queryByCond(param, this.pageSize, this.pageNum)
          .then(response => {
            const data = response.data
            if (data.code === 200) {
              const data = response.data.data

              this.tableData.list = data.list
              this.tableData.total = data.total

            } else {
              Message.error(data.message)
              reject()
            }
            this.queryLoading = false
          })
          .catch(error => {
            if (error.message !== '') {
              //Message.error(error.message)
            }
            this.queryLoading = false
            reject(error)
          })
      })
    },
    handleAdd() {
      this.mode = 'add'
      this.currentRecord = {}
      this.showEditDialog = true
    },
    handleDetail(row) {
      this.mode = 'details'
      this.currentRecord = Object.assign({}, row)
      this.showEditDialog = true
    },
    handleEdit(row) {
      this.mode = 'edit'
      this.currentRecord = Object.assign({}, row)
      this.showEditDialog = true
    },

    // 处理翻页事件
    handlePageChange(currentPage) {
      this.pageNum = currentPage
      this.query()
    },
    // 处理页面总条数事件
    handleSizeChange(val) {
      this.pageSize = val;
      this.query()
    },
    // 处理对话框关闭事件
    handleDialogClose(done) {
      this.$refs.editForm.resetFields()
      done()
    },
    handleDel(row) {
      this.$confirm('确定删除吗？', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          const param = Object.assign({}, row)
          SafetyCheckApi
            .delete(param)
            .then(response => {
              const data = response.data
              if (data.code === 200) {
                this.$message({
                  message: '删除成功',
                  type: 'success'
                })
                this.handleQuery()
              } else {
                Message.error(data.message)
              }
            })
            .catch(error => {
              //console.log(error)
              if (error.message !== '') {
                //Message.error(error.message)
              }
            })
        }).catch(() => {
        })
    },
    // 处理编辑对话框关闭事件
    handleAfterEdit() {
      this.showEditDialog = false
      this.$refs.editForm.resetFields()
      this.query()
    },
    handleDao(id, name, time) {
      SafetyCheckApi.daoWord({ id }).then(res => {
        if (res.data) {
          const elink = document.createElement('a');
          elink.download = `${name}-${parseTime(time, '{y}-{m}-{d}')}-一班三查.docx`;
          elink.style.display = 'none';
          const blob = new Blob([res.data], { type: 'application/x-msdownload' });
          elink.href = URL.createObjectURL(blob);
          document.body.appendChild(elink);
          elink.click();
          document.body.removeChild(elink);
        } else {
          this.$message.error('导出异常请联系管理员');
        }
      })
    },
    handleChange() {
      this.$refs.searchForm.resetFields()
      this.query()
    }
  }
}
</script>
<style>
.container {
  margin: 10px;
}

.table-container {
  margin-top: 0px;
}

.pagination-container {
  margin-top: 30px;
  text-align: right;
}
</style>
